package com.savi.myapplication.config;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;

import androidx.appcompat.widget.AppCompatEditText;

import com.savi.myapplication.R;

/**
 * Copyright (c) 2017,赛维航电科技有限公司产品研发部
 * All rights reserved.
 *
 * @author YangHao  @version V1.0     @date 2019/2/30.
 * @file EfbEditText.java
 * @brief
 */

public class EfbEditText extends AppCompatEditText {

    int maxContentLength = 25;

    public EfbEditText(Context context){

        super(context);

    }

    /**
     *
     * @param context
     * @param attrs
     */
    public EfbEditText(Context context, AttributeSet attrs) {

        super(context, attrs);
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.EfbEditText);
        int tempLength = array.getInt(R.styleable.EfbEditText_max_content_length, 0);
        if(tempLength != 0)
            maxContentLength = tempLength;

        this.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {

                if(editable.length() > maxContentLength){

                    AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), AlertDialog.THEME_TRADITIONAL);
                    builder.setMessage(getContext().getString(R.string.char_overlength) + maxContentLength );
                    builder.setTitle(R.string.hint_hint);
                    builder.setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            //设置你的操作事项
                        }
                    });

                    String subString = editable.toString().substring(0, maxContentLength);
                    EfbEditText.this.setText(subString);
                    EfbEditText.this.setSelection(maxContentLength);
                    builder.show();

                }
            }
        });

    }

    /**
     *
     * @param context
     * @param attrs
     * @param defStyleAttr
     */
    public EfbEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

}
